﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using HRM.Model;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;

namespace HRM.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class LoginViewModel : ViewModelBase
    {
        private IUserService _service;
        private string _userName = string.Empty;

        public string UserName
        {
            get { return _userName; }
            set
            {
                if (_userName != value)
                {
                    _userName = value;
                    RaisePropertyChanged("UserName");
                }
            }
        }

        private bool _loading = false;

        public bool Loading
        {
            get { return _loading; }
            set
            {
                if (_loading != value)
                {
                    _loading = value;
                    RaisePropertyChanged("Loading");
                }
            }
        }

        public RelayCommand<PasswordBox> LoginCommand
        {
            get
            {
                return new RelayCommand<PasswordBox>(async (password) =>
                {
                    if (UserName != "" && password.Password != "")
                    {
                        Loading = true;
                        bool vadidate = false;
                        await Task.Run(() =>
                        {
                            vadidate = _service.Login(UserName, password.Password);
                        });
                        Loading = false;
                        if (vadidate)
                        {
                            SimpleIoc.Default.Register<NguoiSuDung>(() => _service.GetUser(UserName));
                            MainWindow window = new MainWindow();
                            App.Current.MainWindow.Close();
                            window.Show();
                        }
                        else MessageBox.Show("Sai tên đăng nhập hoặc mật khẩu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                    }
                });
            }
        }

        /// <summary>
        /// Initializes a new instance of the LoginViewModel class.
        /// </summary>
        public LoginViewModel(IUserService service)
        {
            _service = service;
        }
    }
}